package jdbc.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @author DCSGO
 * @version 1.0
 * JDBC工具类
 * 连接数据库 关闭资源
 */
public class JDBCUtils {
    private static final String Driver;
    private static final String url;
    private static final String user;
    private static final String password;

    static {
        try {
            Properties properties = new Properties();
            properties.load(new FileInputStream("src\\mysql.properties"));
            Driver = properties.getProperty("Driver");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
        } catch (IOException e) {
            //将编译异常转换为运行异常 调用者既可以选择将异常捕获以进行处理
            //也可以默认处理(交由JVM处理) 提高了灵活性 推荐该做法
            throw new RuntimeException(e);
        }
    }

    //获取与 mysql 数据库的连接
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //关闭相关资源 结果集 Statement 或 PrepareStatement Connection
    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
